<template>
  <t-dialog :visible="visible" :close-on-overlay-click="false" :header="isEdit ? '编辑炼厂' : '新建炼厂'" :width="640"
    :footer="false" @close="onClose">
    <template #body>
      <div class="add-refinery-form">
        <t-form ref="form" :data="formData" :rules="rules" label-width="80px">
          <t-form-item label="名称：" name="name">
            <t-input v-model="formData.name" placeholder="请输入炼厂名称" />
          </t-form-item>

          <t-form-item label="地址：" name="address">
            <t-input v-model="formData.address" placeholder="请输入炼厂地址" />
          </t-form-item>

          <div class="divider"></div>

          <div class="oil-types">
            <t-checkbox-group v-model="formData.oilTypes">
              <t-checkbox value="92#">92#</t-checkbox>
              <t-checkbox value="95#">95#</t-checkbox>
              <t-checkbox value="98#">98#</t-checkbox>
              <t-checkbox value="92#E">92#E</t-checkbox>
              <t-checkbox value="95#E">95#E</t-checkbox>
            </t-checkbox-group>

            <t-checkbox-group v-model="formData.oilTypes" class="mt-16">
              <t-checkbox value="-0#">-0#</t-checkbox>
              <t-checkbox value="-10#">-10#</t-checkbox>
              <t-checkbox value="-20#">-20#</t-checkbox>
              <t-checkbox value="-35#E">-35#E</t-checkbox>
            </t-checkbox-group>
          </div>

          <div class="divider"></div>

          <!-- 根据勾选的油品类型显示对应的库存输入框 -->
          <template v-for="oilType in formData.oilTypes" :key="oilType">
            <t-form-item :label="`${oilType}库存数量：`" :name="`stock${oilType}`">
              <t-input v-model="formData.stockMap[oilType]" :placeholder="`请输入${oilType}库存数量`" />
            </t-form-item>
          </template>
        </t-form>

        <div class="form-footer">
          <t-button theme="primary" @click="onSubmit">确定</t-button>
        </div>
      </div>
    </template>
  </t-dialog>
</template>

<script lang="ts">
import { ref, reactive, defineComponent, watch, onMounted } from 'vue';

// 导出为默认组件
const AddRefineryDialog = defineComponent({
  name: 'AddRefineryDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['close', 'submit'],
  setup(props, { emit }) {
    const form = ref();
    const formData = reactive({
      id: '',
      name: '',
      address: '',
      oilTypes: [],
      stockMap: {} as Record<string, string>
    });

    const rules = {
      name: [{ required: true, message: '请输入炼厂名称', trigger: 'blur' }],
      address: [{ required: true, message: '请输入炼厂地址', trigger: 'blur' }]
    };

    // 监听油品类型变化，确保stockMap中有所有选中类型的键
    watch(() => [...formData.oilTypes], (newTypes) => {
      // 处理新增的类型
      newTypes.forEach(type => {
        if (!formData.stockMap[type]) {
          formData.stockMap[type] = '';
        }
      });

      // 移除未选中类型的库存数据
      Object.keys(formData.stockMap).forEach(key => {
        if (!newTypes.includes(key)) {
          delete formData.stockMap[key];
        }
      });
    });

    // 监听编辑数据，填充表单
    watch(() => props.editData, (newData) => {
      if (props.isEdit && newData && Object.keys(newData).length > 0) {
        fillFormData(newData);
      }
    }, { immediate: true, deep: true });

    // 监听弹窗显示状态
    watch(() => props.visible, (visible) => {
      if (visible && props.isEdit && props.editData) {
        fillFormData(props.editData);
      } else if (visible && !props.isEdit) {
        resetForm();
      }
    });

    // 填充表单数据
    const fillFormData = (data: any) => {
      formData.id = data.id || '';
      formData.name = data.name || '';
      formData.address = data.address || data.province || '';

      // 当前油品作为选中类型
      formData.oilTypes = [];
      if (data.currentOil) {
        formData.oilTypes.push(data.currentOil);
      }

      // 清空之前的库存映射
      formData.stockMap = {};

      // 设置库存数据
      if (data.currentOil) {
        formData.stockMap[data.currentOil] = data.totalStock?.replace('KG', '') || '';
      }
    };

    const onClose = () => {
      emit('close');
    };

    const onSubmit = async () => {
      const valid = await form.value?.validate?.();
      if (valid === true) {
        // 将数据整理为提交格式
        const submitData = {
          id: formData.id,
          name: formData.name,
          address: formData.address,
          oilTypes: formData.oilTypes,
          stocks: { ...formData.stockMap }
        };

        emit('submit', submitData);
        if (!props.isEdit) {
          // 如果是新增，则重置表单
          resetForm();
        }
      }
    };

    const resetForm = () => {
      formData.id = '';
      formData.name = '';
      formData.address = '';
      formData.oilTypes = [];
      formData.stockMap = {};
      form.value?.reset?.();
    };

    return {
      form,
      formData,
      rules,
      onClose,
      onSubmit
    };
  }
});

export default AddRefineryDialog;
</script>

<style lang="less" scoped>
.add-refinery-form {
  padding: 8px;

  .divider {
    height: 1px;
    background-color: #eee;
    margin: 16px 0;
  }

  .oil-types {
    margin: 24px 0;
  }

  .mt-16 {
    margin-top: 16px;
  }

  .form-footer {
    display: flex;
    justify-content: center;
    margin-top: 32px;
  }
}
</style>